
import {
  api,
  util, 
  dialog,
  forms, 
  clickIncrement,
  clearIncrement
} from '../../../../js/util'; 
import {
  router
} from '../../../../js/router';
import {
  address
} from '../../../../js/modules/store';
import {
  area
} from "../../../../js/modules/gloab";
import authorize from '../../../../js/modules/authorize';
import {
  config
} from "../../../../js/modules/gloab";
var app = getApp();
import BasePage from '../../../../js/common/base-page'
import { chooseAddress, chooseLocation } from '../../../../js/authSetting';
import { isEmpty } from '../../../../js/newUtil';
let addressList = []
let addressIndex = 0
BasePage({
  pageKey:"addressList",

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX:app.globalData.isIphoneX,
    mainColor:api.titleColor||"#e56b14",//主题色
    oldAdr: {},
    addrlist: [],
    editAdr: [],
    isEdit: false,
    isAdd: true,
    region: [],
    tree:[],
    isDefault:true,
    multiArray:[[],[],[]],
    multiIndex: [0, 0, 0],
    multiArrayObject: [[], [], []],
    editStatus: false, //操作状态
    forbidDeliveryEdit:false,
    editToDetail:false,   //点击整行能否进入详情（默认点击图标才能进入详情）
    readerValue:'',
    currentNum:0,
    smartAdress:{},
    errorCount:1,
    keyword:'',//关键词搜索
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    //从个人中心页进入改变点击详情区域
    if(options.pagetype=='1'){
      that.setData({
        editToDetail:true
      })
    };
    this.findAdress(options.id);
    this.loadAdressList();
    this.getWholesaleConfig(); 
    // var address = area.getCacheLocation();
    // if (address.Code!=""){
    //   that.data.region[0] = address.Province;
    //   that.data.region[1] = address.City;
    //   that.data.region[2] = address.Area;
    //   this.setData({
    //     region: that.data.region
    //   })
    // }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    addressList = []
    addressIndex = 0
    clearIncrement();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let list = this.data.addrlist
    addressIndex = addressIndex + 1
    list = [...list, ...addressList.slice(addressIndex * 50, (addressIndex + 1) * 50)]
    this.setData({
      addrlist: list
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**加载已选择的地址 */
  findAdress(id) {
    let that = this;
    address.findAdress(id, function (content) {
      if(content&&content.length>0){
      that.setData({
        oldAdr: content[0]
      });
      }
    });
  },
  /**加载地址列表 */
  loadAdressList() {
    let that = this;
    address.loadUserAddressList(that.data.keyword,function (content) {
      addressList = content || []
      addressIndex = 0
      let list = []
      if (addressList.length <= 50) {
        list = addressList
      } else {
        list = addressList.slice(addressIndex * 50, (addressIndex + 1) * 50)
      }
      that.setData({
        addrlist: list
      });
    });
  },
  /**新增地址 */
  addShowAddress(e) {
    let { forbidDeliveryEdit,region } = this.data;
    if (forbidDeliveryEdit) {
      util.tips("系统当前设置禁止订货商编辑收货地址");
      return;
    }
    this.setData({
      isAdd: true,
      isEdit: true,
      editAdr: { Id: 0, OldDefault: 0, IsDefault: 0 }
    });
    if (region!=[]){
      this.getLocation();
    }
    else{
      this.getLocation();
    }
  },
  getLocation(){
    app.getCurrentLocation(api.amapKey,(res) => {
      if(res){
        var region = [res.province || '北京市',res.city || '北京市',res.district|| '东城区', res.town || '东华门街道'];
        var editAdr = this.data.editAdr;
        editAdr.Province = region[0];
        editAdr.City = region[1];
        editAdr.Area = region[2];
        editAdr.Town = region[3];
        editAdr.TownId = res.towncode
        this.setData({
          region:region,
          editAdr:editAdr
        })
      }
    })
  },
  /**编辑地址 */
  editShowAddress(e) {
    let { forbidDeliveryEdit}=this.data;
    if (forbidDeliveryEdit){
      util.tips("系统当前设置禁止订货商编辑收货地址");
      return;
    }
    var idx = e.currentTarget.dataset.idx;
    var addrlist = this.data.addrlist;
    var editAdr = addrlist[idx];
    editAdr.IsDefault = editAdr.IsDefault == false || editAdr.IsDefault == 0 ? 0 : 1;
    editAdr.OldDefault = editAdr.IsDefault;
    editAdr.detail = editAdr.Address?editAdr.Address.replace(/()+/ig, "\n"):editAdr.Address
    this.setData({
      isAdd: false,
      isEdit: true,
      editAdr: editAdr,
      readerValue:'',
      currentNum:0,
      region:[editAdr.Province, editAdr.City, editAdr.Area, editAdr.Town]
    });
  },
 
  /**选择新的地址*/
  selectedAdress(e) {
    let {editToDetail} = this.data;
    //点击整行打开编辑页面
    if(editToDetail){
      this.editShowAddress(e);
    }else{
      var idx = e.currentTarget.dataset.idx;
      var addrlist = this.data.addrlist;
      var defaultAdr = addrlist[idx];

      var consignee = {
        AddressId: defaultAdr.Id,
        Province: defaultAdr.Province,
        City: defaultAdr.City,
        Area: defaultAdr.Area,
        Address: defaultAdr.Address,
        Name: defaultAdr.Name,
        Mobile: defaultAdr.Mobile
      }
      router.navigateBack({
        defaultAdr: defaultAdr,
        consignee: consignee
      });
    }
  },
  /**
 * 地区选择
 */
  bindRegionChange: function (e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value);
    var region = e.detail.value;
    region = this.transRegion(region)
    var editAdr = this.data.editAdr;
    editAdr.Province = region[0];
    editAdr.City = region[1];
    editAdr.Area = region[2];
    editAdr.Town = region[3];
    this.setData({
      region: region,
      editAdr: editAdr
    })
  },
  showPicker () {
    let that = this
    let editAdr = this.data.editAdr
    let picker = this.selectComponent('#pickerStreet')
    picker.$$showComponent({
      Id: editAdr.TownId || '',
      success (res) {
        console.log('选择的省市区街数据', res)
        let region = res.chineseValue
        editAdr.Province = region[0]
        editAdr.City = region[1]
        editAdr.Area = region[2]
        editAdr.Town = region[3]
        editAdr.TownId = res.streetId
        that.setData({
          region: region,
          editAdr: editAdr
        })
      }
    })
  },
  //设置定位当前地址
  setLocation:function(){
    var that=this;
    let {region,editAdr} = that.data;
    chooseLocation({
      success: res => {
        console.log(res)
        if(res.address){
          let newAddress;
          try{
            that.smartAddress(res.address,true);
          }catch (e){
            util.tips('输入的格式不正确，请重新输入！');
          };
          setTimeout(function(){
            newAddress = that.data.smartAdress;
            console.log(newAddress,'=====1');
            that.setData({
              'editAdr.Province':newAddress.province,
              'editAdr.City':newAddress.city,
              'editAdr.Area':newAddress.area,
              'editAdr.Town':newAddress.town,
              'editAdr.Address':newAddress.detail,
              region:[newAddress.province,newAddress.city,newAddress.area]
            }
            )
          },1000)
        }
      }
    })
  },
  
  /**设置是否默认 */
  switchDefault(e) {
    var editAdr = this.data.editAdr;
    editAdr.IsDefault = e.detail.value == true ? 1 : 0;
    this.setData({ editAdr: editAdr });
  },
  /**文本框的修改*/
  addressInput(e) {
    var editAdr = this.data.editAdr;
    var name = e.currentTarget.dataset.name;
    switch (name) {
      case "Name":
        editAdr.Name = e.detail.value;
        break;
      case "Mobile":
        editAdr.Mobile = e.detail.value;
        break;
      case "Address":
        editAdr.Address = e.detail.value;
        break;
    }
    this.setData({ editAdr: editAdr });
  },
  /**验证地址*/
  validateAdress(editAdr) {
    if(!editAdr.Name || !editAdr.Name.replace(/(^\s*)|(\s*$)/g,"")){
      util.tips("请输入正确的收货人姓名");
      return;
    }
    // var nameItem = {
    //   value: util.trim(editAdr.Name),
    //   validate: "isnull|name",
    //   error: "请输入正确的收货人姓名,仅支持中文、英文、数字、连字符、下划线、空格"
    // }
    // if (!forms.validate(nameItem)) return false;
    var mobileItem = {
      value: util.trim(editAdr.Mobile),
      validate: "isnull|mobile",
      error: "请输入正确的手机号"
    }
    if (!forms.validate(mobileItem)) return false;

    if (editAdr.Province == "" || editAdr.Province == undefined) {
      util.tips("请选择省份");
      return false;
    }
    if (editAdr.City == "" || editAdr.City == undefined) {
      util.tips("请选择市");
      return false;
    }
    if (editAdr.Area == "" || editAdr.Area == undefined) {
      util.tips("请选择地区");
      return false;
    }
    // 部分地区无第四级的地址，所以街道不必填(如澳门)
    // if (isEmpty(editAdr.Town)) {
    //   util.tips("请选择街道");
    //   return
    // }
    if(!editAdr.Address || !editAdr.Address.replace(/(^\s*)|(\s*$)/g,"")){
      util.tips("请输入正确的详细地址");
      return;
    }
    return true;
  },
  /**保存地址 */
  saveAdress() {
    var that = this;
    //设置为编辑状态 防止重复提交
    if (this.data.editStatus) return;
    this.setData({
      editStatus: true
    });
    var editAdr = this.data.editAdr;
    var oldAdr = this.data.oldAdr;
    if (!this.validateAdress(editAdr)) {
      that.setData({
        editStatus: false
      });
      return;
    }
    clickIncrement(function () {
      if (parseInt(editAdr.Id) > 0) {
        //修改
        address.modifyAddress(editAdr, function (status) {
          if (status) {
            that.loadAdressList();
            if (editAdr.Id == oldAdr.Id) {
              oldAdr = editAdr;
            }
            else if (editAdr.IsDefault == 1) {
              oldAdr.IsDefault = 0;
            }
            that.setData({
              isEdit: false,
              oldAdr: oldAdr,
              editStatus: false
            });
          }else{
            that.setData({
              editStatus: false
            });
          }
        });
      } else {
        //增加
        address.addAddress(editAdr, function (status) {
          if (status) {
            that.loadAdressList();
            if (editAdr.IsDefault == 1) {
              oldAdr.IsDefault = 0;
              that.setData({
                oldAdr: oldAdr
              });
            }
            that.setData({
              isEdit: false,
              editStatus: false
            });
          } else {
            that.setData({
              editStatus: false
            });
          }
        });
      }
    });
  },
  /**取消*/
  cancelAdress() {
    this.setData({
      isAdd: true,
      isEdit: false
    });
  },
  /**删除地址 */
  deleteAdress(evt) {
    var that = this;
    util.confirm(function () {
      var id = evt.currentTarget.dataset.id;
      address.deleteAddress(id, function (res) {
        that.loadAdressList();
        that.setData({
          isEdit: false
        });
      });
    }, null, "您确定要删除此收货地址吗?"," ");
  },
  /*
  *加载配置项参数
   */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Store",
       (model)=> {
         let forbidDeliveryEdit = model.ForbidDeliveryEdit;
         console.log(forbidDeliveryEdit,'======');
         that.setData({
           forbidDeliveryEdit: forbidDeliveryEdit
         }, () => {
           if (!forbidDeliveryEdit) {
             //that.load_area();
           }
         });
      });
  },
  //调用原生地址添加
  addNativeAddress(){
    let that = this;
    chooseAddress({
      success:(res)=>{
        let wxAdr = {};
        wxAdr.Province = res.provinceName.replace("省","");
        wxAdr.City = res.cityName.replace("市","");
        wxAdr.Area = res.countyName;
        wxAdr.Name = res.userName;
        wxAdr.Mobile = res.telNumber;
        wxAdr.Address = res.detailInfo;
        wxAdr.IsDefault = 0;
        that.setData({
          isEdit: true,
          editAdr: wxAdr,
          isDefault:false
        },()=>{
        });
        
      }
    })
  },
  /**
   * 更改智能识别文本域 
   */
  changeReaderValue:function(e){
    let value = e.detail.value;
    this.setData({
      readerValue:value,
      currentNum:value.length
    })
  },
  /**
   * 清空智能识别文本域
   */
  clearReader(){
    this.setData({
      readerValue:'',
      currentNum:0
    })
  },
  /**
   * 智能识别
   */
  discernReader(){
    let that = this;
    if(!this.data.readerValue){
      util.tips('输入的格式不正确，请手动输入');
      return;
    }
    // replace(/[\r\n]/g, "")---去掉换行  replace(/\↵+$/g,'')--去掉特殊字符↵
    let value = util.trim(this.data.readerValue.replace(/[\r\n]/g, " ")).split(/[ ,， ]+/);
    let originAdress; 
    let readerAddress = {};
    let regName = /^[\u4E00-\u9FA5]{2,4}$/;
    let regPhone = /^0?(13|14|15|16|17|18|19)[0-9]{9}$/;
    for(let i = 0;i<value.length;i++){
      if(regPhone.test(value[i].replace(/\↵+$/g,''))){
        readerAddress.Mobile = value[i];
      }else if(regName.test(value[i].replace(/\↵+$/g,''))){
        readerAddress.Name = value[i];
      }else{
        originAdress = value[i]; 
      }
    };
    if (originAdress==undefined||originAdress=='') {
      util.tips('请输入解析地址！');
      return;
    }
    let newAddress;
    try{
      that.smartAddress(originAdress,true);
    }catch (e){
      util.tips('输入的格式不正确，请重新输入！');
    };
    setTimeout(function(){
      newAddress = that.data.smartAdress;
      readerAddress.Name = readerAddress.Name;
      readerAddress.Mobile = readerAddress.Mobile;
      readerAddress.Province = newAddress.province;
      readerAddress.City = newAddress.city;
      readerAddress.Area = newAddress.area;
      readerAddress.Address = newAddress.detail;
      that.setData({
        editAdr:readerAddress,
        region:[readerAddress.Province,readerAddress.City,readerAddress.Area]
      }
      )
    },1000)
  },
  changtext(){
    var that =this;
    let value = util.trim(this.data.readerValue.replace(/[\r\n]/g, " "));
    if (value.indexOf(',')>-1) {
      value = value.split(',');
    }else if (value.indexOf('，')>-1) {
      value = value.split('，');
    }else {
      value = value.split(' ');
    }
    let originAdress; 
    let readerAddress = {};
    var mobileReg = /(13|14|15|16|17|18|19)[0-9]{9}/;  
    var phoneReg = /\d{3}-\d{8}|\d{4}-\{7,8}/;
    var areaReg = new RegExp(/.+?(省|市|自治区|自治州|县|区|路|街|道|里|号|栋|楼)/g);
    for(let i = 0;i<value.length;i++){
      var item = value[i].replace(/^\s+|\s/g,'');
      var mobile = item.match(mobileReg);
      var phone = item.match(phoneReg);
      if(mobile && mobile.length > 0 && !readerAddress.Mobile){
        readerAddress.Mobile = mobile[0];
      }else if(phone && phone.length > 0 && !readerAddress.Mobile){
        readerAddress.Mobile = phone[0];
      }else if(areaReg.test(item)){
        originAdress = item;
      }else{
        readerAddress.Name = item;
      }
    };
    if (originAdress==undefined||originAdress=='') {
      util.tips('请输入解析地址！');
      return;
    }
    let newAddress;
    try{
      that.smartAddress(originAdress,true);
    }catch (e){
      util.tips('输入的格式不正确，请重新输入！');
    };
    setTimeout(function(){
      newAddress = that.data.smartAdress;
      readerAddress.Name = readerAddress.Name;
      readerAddress.Mobile = readerAddress.Mobile;
      readerAddress.Province = newAddress.province;
      readerAddress.City = newAddress.city;
      readerAddress.Area = newAddress.area;
      readerAddress.Address = newAddress.detail;
      readerAddress.Town = newAddress.town
      that.setData({
        editAdr:readerAddress,
        region:[readerAddress.Province,readerAddress.City,readerAddress.Area, readerAddress.Town]
      }
      )
    },1000)
  },
  smartAddress(originAdress,parse){
    var that=this;
    var pararm = {
      address:originAdress,
      parse:parse,
    }
    address.addressParse(pararm,function(res){
      var address = res.Content;
      if(!address){return}
      if (address.Area=="JsonData array")address.Area="";
      var provice = originAdress.replace(address.Province,"").replace("省","");
      var city = provice.replace(address.City,"").replace("市","");
      var street = city.replace(address.Area,"");
      if (!address.Town) {
        let matchRes = street.match('街道')
        if (matchRes) {
          let index = matchRes['index']
          address.Town = street.slice(0, index) + '街道'
        }
      }
      that.setData({
        smartAdress:{
          province:address.Province,
          city:address.City,
          area:address.Area,
          town:address.Town,
          townId: address.TownId || address.towncode || '',
          detail:street
        }
      })
    })
  },
  /**
   * 关键词搜索
   */
  onSearchKeywordEvent: function(e) {
    var that = this;
    that.setData({
      keyword:e.detail
    })
    that.loadAdressList();
  },
  /**
   * 转换微信省市区选择器的数据,变为后台需要的数据类型(仅变更直辖市)
   * 在336上已全部采用后台数据,此方法将失效
   * @param {*} region 省市区数组
   */
  transRegion (region = []) {
    let p = region[0]
    let c = region[1]
    if (p.includes('北京') || p.includes('天津') || p.includes('上海')) {
      c = '市辖区'
    }
    if (p.includes('重庆')) {
      if (c.includes('重庆')) {
        c = '市辖区'
      } else {
        c = '县辖区'
      }
    }
    region[1] = c || ''
    return region
  }
})